package com.teamin.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.mysql.cj.core.util.StringUtils;
import com.teamin.config.ErrorCode;
import com.teamin.entity.*;
import com.teamin.enums.TsakContentEnum;
import com.teamin.mapper.*;
import com.teamin.service.*;
import com.teamin.service.Jobs.JobAndTriggerImpl;
import com.teamin.service.labelService.LabelService;
import com.teamin.utils.HttpKit;
import com.teamin.utils.Utils;
import com.teamin.web.exception.GlobalErrorInfoException;
import com.teamin.web.model.ErrorInfo;
import com.teamin.web.model.TaskQueryModel;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.*;

@Component
public class TaskServiceImpl implements TaskService ,Serializable {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private TaskMapper taskMapper;
	@Autowired
	private CircleMapper circleMapper;
	@Autowired
	private MessageMapper messageMapper;
	@Autowired
	private MessageEntityMapper messageEntityMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private NetDiskMapper netDiskMapper;

	@Autowired
	private MessageService messageService;
	@Autowired
	private CircleService circleService;

	@Autowired
	private FileServiceImpl fileService;

	@Autowired
	private NameRuleService nameRuleService;

	@Autowired
	private LogService logService;

	@Autowired
	private LabelService labelService;

	@Autowired
	private WebsocketServiceImpl websocketService ;


	@Autowired
	private JobAndTriggerImpl jobAndTrigger;

	@Autowired
	private INetDiskService netDiskService;

	@Override
	public int deleteTaskById(Long id,Long controlUser,Long circleId,String userFlag) throws GlobalErrorInfoException {
		TaskEntity ta = selectTaskBase(id);
		try {
			int result = taskMapper.deleteTask(id);
			if (result == 0) {
				throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.DELETE_TASK_FAIL));
			}
			//删除任务发圈子消息中去
			logService.insertCircleLog(circleId, LogService.HANDLE.DELETE, LogService.CircleHandleField.CIRCLE_TASK,controlUser,circleService.getUserName(circleId,controlUser),ta.getTaskName()) ;

			JSONObject json = new JSONObject();
			json.put("taskId",id) ;
			json.put("parentTaskId",ta.getParentTaskId()) ;

			//发送socket通知
			websocketService.sendCircle(controlUser,circleId, WebsocketService.CirclePropertise.TASK, WebsocketService.Control.DELETE,json,userFlag);
			//发送任务的同步
			websocketService.sendTask(controlUser,circleId,id, WebsocketService.TaskPropertise.BASE, WebsocketService.Control.DELETE,id,userFlag);
			//删除任务的消怎通知,公众号订阅号,及时通知
			messageService.deleteTaskMessage(ta,getCirclesByTask(ta.getTaskId(), controlUser),controlUser,userFlag);

			return result;
		} catch (Exception e) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.INTERNAL_SERVER_ERROR, ErrorCode.DELETE_TASK_FAIL));
		}
	}

	@Override
	public long addTask(TaskEntity record) throws GlobalErrorInfoException {
		try {
			int result = taskMapper.addTask(record);
			if (result == 0) {
				throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.ADD_TASK_FAIL));
			}
			return record.getTaskId();
		} catch (Exception e) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.INTERNAL_SERVER_ERROR, ErrorCode.ADD_TASK_FAIL));
		}
	}

	@Override
	public TaskEntity selectTaskById(Long taskId){
		TaskEntity taskEntity = taskMapper.selectByTask(taskId);

		if (taskEntity != null) {
			taskEntity.setUserList(getAttention(taskId));
			taskEntity.setCommentList(getComment(taskId));
			taskEntity.setSubTask(selectSubTask(taskId));
		}

		return taskEntity;
	}

	@Override
	public TaskEntity selectTaskBase(Long taskId){
		TaskEntity taskEntity = taskMapper.selectBaseTask(taskId);
		return taskEntity;
	}

	/**
	 * 查询任务的子任务
	 * @return TaskEntity
	 */
	@Override
	public List<TaskEntity> selectSubTask(Long parentTaskId){
		return taskMapper.selectSubTask(parentTaskId) ;
	}

	@Override
	public TaskEntity selectTaskV010AndCommentAndAttentionUser(Long taskId, Long userId, Long circleId) throws GlobalErrorInfoException {
		TaskEntity taskEntity = taskMapper.selectTaskV010(taskId,userId,circleId);

		if (taskEntity == null) {
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.NOT_FOUND, ErrorCode.FIND_TASK_FAIL));
		}
		taskEntity.setUserList(getAttention(taskId));
		taskEntity.setCommentList(getComment(taskId));
		taskEntity.setSubTask(selectSubTask(taskId));
		return taskEntity;
	}

	@Override
	public int setTaskStateDelete(Long taskId) throws GlobalErrorInfoException {
		try {
			int result = taskMapper.deleteTask(taskId);
			if (result == 0) {
				throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.UPDATE_TASK_FAIL));
			}
			return result;
		} catch (Exception e) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.INTERNAL_SERVER_ERROR, ErrorCode.UPDATE_TASK_FAIL));
		}
	}

	@Override
	public long updateTask(TaskEntity record, Long controlUserId,String planFinishTime) throws GlobalErrorInfoException {
		try {
			TaskEntity old = taskMapper.selectByTask(record.getTaskId());;
			int result = taskMapper.updateTask(record,controlUserId);

			addTaskLog(record,controlUserId,planFinishTime,old);
			if (result == 0) {
				throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.UPDATE_TASK_FAIL));
			}
			return record.getTaskId();
		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.INTERNAL_SERVER_ERROR, ErrorCode.UPDATE_TASK_FAIL));
		}
	}

	private void addTaskLog(TaskEntity record, long controlUserId,String planFinishTime,TaskEntity old) {
		//删除任务发圈子消息中去

		//修改执行者的日志
		if(record.getAssignerId() != null) {
			if(record.getAssignerId()==0) {
				logService.insertTaskLog(record.getTaskId(),LogService.HANDLE.CLEAR, LogService.TaskHandleField.TASK_ASSIGNER,controlUserId,getUserNameByTask(record.getTaskId(),controlUserId),getUserNameByTask(record.getTaskId(),old.getAssignerId())) ;
			}else {
				logService.insertTaskLog(record.getTaskId(),LogService.HANDLE.MODIFY, LogService.TaskHandleField.TASK_ASSIGNER,controlUserId,getUserNameByTask(record.getTaskId(),controlUserId),getUserNameByTask(record.getTaskId(),record.getAssignerId())) ;
			}

		}

		//修改任务的标题的日志
		if(record.getTaskName() != null && !record.getTaskName().equals(old.getTaskName())) {
			logService.insertTaskLog(record.getTaskId(), LogService.HANDLE.MODIFY, LogService.TaskHandleField.TASK_NAME,controlUserId,getUserNameByTask(record.getTaskId(),controlUserId),record.getTaskName()) ;
		}

		//修改任务的描述的日志
		if(record.getDescription() != null && !record.getDescription().equals(old.getDescription())) {
			logService.insertTaskLog(record.getTaskId(), LogService.HANDLE.MODIFY, LogService.TaskHandleField.TASK_DESCRIPTION,controlUserId,getUserNameByTask(record.getTaskId(),controlUserId),record.getDescription()) ;
		}

		//修改任务的截止时间
		if(record.getPlanFinishTime() != null) {
			logService.insertTaskLog(record.getTaskId(), LogService.HANDLE.MODIFY, LogService.TaskHandleField.TASK_PLAN_FINISH_TIME,controlUserId,getUserNameByTask(record.getTaskId(),controlUserId), Utils.getFormatDateTime(record.getPlanFinishTime().getTime())) ;
		}else if(planFinishTime != null && planFinishTime.equals("")){
			logService.insertTaskLog(record.getTaskId(), LogService.HANDLE.CLEAR, LogService.TaskHandleField.TASK_PLAN_FINISH_TIME,controlUserId,getUserNameByTask(record.getTaskId(),controlUserId),null) ;
		}

	}

	@Override
	public Long selectCircleIdByTask(Long taskId, Long userId) {
		return circleMapper.selectCircleIdByTask(taskId,userId);
	}

	public CircleEntity getCirclesByTask(Long taskId,Long userId) {
		return circleMapper.selectCirclesByTask(taskId,userId);
	}

	@Override
	public int addTaskToCircle(TaskEntity taskEntity,Long circleId,Long controlUser) throws GlobalErrorInfoException {

		long taskId = addTask(taskEntity);
		try {
			int result = taskMapper.addTaskToCircle(circleId, taskId);
			if (result == 0) {
				throw new GlobalErrorInfoException(
						new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.ADD_TASK_TO_CIRCLE_FAIL));
			}
			//新增任务的日志
			logService.insertTaskLog(taskId, LogService.HANDLE.CREATE, LogService.TaskHandleField.TASK,controlUser,getUserNameByTask(taskId,controlUser),taskEntity.getTaskName()) ;
			//修改任务的截止时间
			if(taskEntity.getPlanFinishTime() != null) {
				logService.insertTaskLog(taskEntity.getTaskId(), LogService.HANDLE.MODIFY, LogService.TaskHandleField.TASK_PLAN_FINISH_TIME,controlUser,getUserNameByTask(taskEntity.getTaskId(),controlUser), Utils.getFormatDateTime(taskEntity.getPlanFinishTime().getTime())) ;
			}
			//修改执行者的日志
			if(taskEntity.getAssignerId() != null) {
				logService.insertTaskLog(taskEntity.getTaskId(),LogService.HANDLE.MODIFY, LogService.TaskHandleField.TASK_ASSIGNER,controlUser,getUserNameByTask(taskEntity.getTaskId(),controlUser),getUserNameByTask(taskEntity.getTaskId(),taskEntity.getAssignerId())) ;
			}

			return result;
		} catch (Exception e) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.INTERNAL_SERVER_ERROR, ErrorCode.ADD_TASK_TO_CIRCLE_FAIL));
		}
	}

	@Override
	public List<TaskEntity> selectByCircle(Long circleId, Integer order,String filter) {
		List<TaskEntity> l = new ArrayList<>() ;

		List<TaskEntity> nomallTasks = taskMapper.selectByCircle(circleId, order,filter);
		if(nomallTasks != null) {
			l.addAll(nomallTasks) ;
		}
		List<TaskEntity> finishTasks = taskMapper.selectFinishTask(circleId,filter);;
		if(finishTasks != null) {
			l.addAll(finishTasks) ;
		}
		return l;
		
	}

	@Override
	public List<TaskEntity> selectByCircleV010(Long circleId, Integer order, String filter,List<String> labels,Long userId,int state,String assignerId) {
		 return taskMapper.selectByCircleV010(circleId,order,filter,labels,userId,state,assignerId) ;
	}

	@Override
	public int addAttention(Long taskId, Long userId) throws GlobalErrorInfoException {
		try {
			int result = taskMapper.addAttention(taskId, userId);
			if (result == 0) {
				throw new GlobalErrorInfoException(
						new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.ADD_ATTEN_TO_TASK_FAIL));
			}
			return result;
		} catch (Exception e) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.INTERNAL_SERVER_ERROR, ErrorCode.ADD_ATTEN_TO_TASK_FAIL));
		}
	}
	@Override
	public int updateAttentions(Long taskId, ArrayList<Long> userIds, Long controlUserId) throws GlobalErrorInfoException {

		Set<Long> attentions = getAttentionUserId(taskId);
		Set<Long> fromUsers = new HashSet<>();
		StringBuffer sb = new StringBuffer() ;
		
		// 添加关注者
		for (Long userId : userIds) {
			fromUsers.add(userId) ;
			// 用户不存在于任务所在圈子
			if (!userHasTask(userId, taskId)) {
				// throw new GlobalErrorInfoException(new
				// ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FIND_USER_NULL));
				continue;
			}

			if(!attentions.contains(userId)) {
				if(StringUtils.isNullOrEmpty(sb.toString())) {
					sb.append(getUserNameByTask(taskId,userId)) ;
				}else {
					sb.append(","+getUserNameByTask(taskId,userId)) ;
				}
				addAttention(taskId, userId);
			}
		}
		if(!StringUtils.isNullOrEmpty(sb.toString())) {
		//修改执行者的日志
			logService.insertTaskLog(taskId,LogService.HANDLE.ADD , LogService.TaskHandleField.TASK_USER_ATTENTION,controlUserId,getUserNameByTask(taskId,controlUserId),sb.toString()) ;
		}

		//删除关注者
		if(attentions != null && attentions.size() !=0 ) {
			Iterator<Long> iter = attentions.iterator();;
			while(iter.hasNext()) {
				Long next = iter.next();;
					if(!fromUsers.contains(next)) {
						removeAttention(taskId,next,controlUserId) ;
					}
			}
		}



		return 1 ;
	}

	@Override
	public int removeAttention(Long taskId, Long userId,Long controlUserId) throws GlobalErrorInfoException {
		try {
			int result = taskMapper.removeAttention(taskId, userId);
			logService.insertTaskLog(taskId,LogService.HANDLE.DELETE , LogService.TaskHandleField.TASK_USER_ATTENTION,controlUserId,getUserNameByTask(taskId,controlUserId),getUserNameByTask(taskId,userId)) ;
			if (result == 0) {
				throw new GlobalErrorInfoException(
						new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.REMOVE_ATTEN_FROM_TASK_FAIL));
			}
			return result;
		} catch (Exception e) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.INTERNAL_SERVER_ERROR, ErrorCode.REMOVE_ATTEN_FROM_TASK_FAIL));
		}
	}
	
	@Override
	public int removeAllAttention(Long taskId,Long controlUserId) {
		try {
			int result = taskMapper.removeAllAttention(taskId);
//			if (result == 0) {
//				throw new GlobalErrorInfoException(
//						new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.REMOVE_ATTEN_FROM_TASK_FAIL));
//			}
			logService.insertTaskLog(taskId,LogService.HANDLE.CLEAR , LogService.TaskHandleField.TASK_USER_ATTENTION,controlUserId,getUserNameByTask(taskId,controlUserId),null) ;
			return result;
		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
			return 0;
//			throw new GlobalErrorInfoException(
//					new ErrorInfo(HttpStatus.INTERNAL_SERVER_ERROR, ErrorCode.REMOVE_ATTEN_FROM_TASK_FAIL));
		}
		
	}

	/**
	 * 获取任务的关注列表
	 * @param taskId 任务ID(必)
	 */
	@Override
	public List<UserEntity> getAttention(Long taskId) {
		return taskMapper.getAttention(taskId);
	}

	/**
	 * 获取任务的关注列表
	 * @param taskId 任务ID(必)
	 */
	@Override
	public Set<Long> getAttentionUserId(Long taskId) {
		return taskMapper.getAttentionUserId(taskId);
	}

	@Override
	public int addComment(CommentEntity commentEntity) throws GlobalErrorInfoException {
		try {
			int result = taskMapper.addComment(commentEntity);
			if (result == 0) {
				throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.ADD_COMMENT_FAIL));
			}

			//如果评论内容类型是File
			if(TsakContentEnum.FILE.getValue().equals(commentEntity.getContentType())){

				try{
					HttpServletRequest request = HttpKit.getRequest();
					Long controlUser = Long.valueOf(request.getAttribute("loginUserId").toString());
					String userFlag = request.getAttribute("userFlag").toString();

					FileEntity fileEntity = this.fileService.getById(Integer.valueOf(commentEntity.getContent()));

					String uuid = fileEntity.getUuid();
					Integer circleId = this.taskMapper.getCircleIdByTaskId(Integer.valueOf(commentEntity.getTaskId().toString()));

					NetDisk netDisk = netDiskMapper.getByUUID(uuid);
					List<NetDisk> netDisks = Lists.newArrayList(netDisk);

					//发送socket通知
					websocketService.sendCircle(controlUser, Long.valueOf(circleId), WebsocketService.CirclePropertise.NET_DISK_FILE_MODIFY, WebsocketService.Control.ADD, netDisks, userFlag);

				}catch (Exception e){
					e.printStackTrace();
					logger.error(e.getMessage());
				}
			}





			return result;
		} catch (Exception e) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.INTERNAL_SERVER_ERROR, ErrorCode.ADD_COMMENT_FAIL));
		}
	}

	@Override
	public List<CommentEntity> getComment(Long taskId)  {
		List<CommentEntity> comment = taskMapper.getComment(taskId);
		for (CommentEntity commentEntity : comment) {
			if(commentEntity.getContentType() == CommentEntity.COMMENT_TYPE_IMG){
				commentEntity.setFileUrl(fileService.getFileUrl(commentEntity.getUuid(),commentEntity.getFileName()));
				if(fileService.supportThumbnailFormat(commentEntity.getSuffix())){
					commentEntity.setThumbnailUrl(fileService.getFileThumbnail(commentEntity.getUuid(),commentEntity.getFileName()));
				}
			}
		}
		return comment ;
	}

	@Override
	public List<TaskEntity> queryTasks(TaskQueryModel taskQueryModel) {
		return taskMapper.queryTasks(taskQueryModel);
	}

	@Override
	public Map<String, Object> getNeedNoticeTasks(Long circleId, Long userId) {

		LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
		// 消息

		// 过期任务
		ArrayList<Object> expiredTasks = new ArrayList<Object>();
		// 三天任务
		ArrayList<Object> threeDaysTasks = new ArrayList<Object>();
		// 7天任务
		ArrayList<Object> sevenDaysTasks = new ArrayList<Object>();
		// 查询7天任务
		Date currentDate = new Date();
		Calendar cal = DateUtils.toCalendar(DateUtils.addDays(currentDate, 3));
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		Date threeDate = cal.getTime();
		Date sevenDate = DateUtils.addDays(threeDate, 4);

		long currentDateLong = currentDate.getTime();
		long threeDateLong = threeDate.getTime();
		long sevenDateLong = sevenDate.getTime();

		TaskQueryModel taskQueryModel = new TaskQueryModel();
		taskQueryModel.setCircleId(circleId);
		taskQueryModel.setAssignerId(userId);
		taskQueryModel.setStateId(0);
		taskQueryModel.setEndDate(sevenDate);

		List<TaskEntity> list = queryTasks(taskQueryModel);
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			TaskEntity taskEntity = (TaskEntity) iterator.next();

			if (taskEntity.getPlanFinishTime() != null) {
				JSONObject jsonObject = (JSONObject) JSON.toJSON(taskEntity);
				long taskTime = taskEntity.getPlanFinishTime().getTime();
				// 三天
				if (taskTime < threeDateLong) {
					jsonObject.put("stateMessage",
							"你有一条任务" + DateFormatUtils.format(taskTime, "M月d日") + "截至，请尽快处理");
					jsonObject.put("stateColor", "#BBBBBB");
					threeDaysTasks.add(jsonObject);
				}
				// 七天
				else if (taskTime < sevenDateLong) {
					int d = (int) ((taskTime - currentDateLong) / 1000 / 60 / 60 / 24) + 1;
					jsonObject.put("stateMessage", d + "天后你有一个任务要处理，请尽快处理");
					jsonObject.put("stateColor", "#CCCCCC");
					sevenDaysTasks.add(jsonObject);
				}
			}
		}

		List<TaskEntity> listExprie = taskMapper.queryExpireTasks(taskQueryModel);
		for (Iterator iterator = listExprie.iterator(); iterator.hasNext();) {
			TaskEntity taskEntity = (TaskEntity) iterator.next();

			if (taskEntity.getPlanFinishTime() != null) {
				JSONObject jsonObject = (JSONObject) JSON.toJSON(taskEntity);
				long taskTime = taskEntity.getPlanFinishTime().getTime();
				// 过期
				if (taskTime <= currentDateLong) {
					int d = (int) ((currentDateLong - taskTime) / 1000 / 60 / 60 / 24);
					if (d == 0) {
						jsonObject.put("stateMessage", "你有一条任务今天截止，请尽快处理");
					} else {
						jsonObject.put("stateMessage", "你有一条任务逾期" + d + "天，请尽快处理");
					}

					jsonObject.put("stateColor", "#AAAAAA");
					expiredTasks.add(jsonObject);
				}
			}
		}

		map.put("expiredTasks", expiredTasks);
		map.put("threeDaysTasks", threeDaysTasks);
		map.put("sevenDaysTasks", sevenDaysTasks);
		return map;
	}

	@Override
	public CommentEntity getCommentById(Long commentId) throws GlobalErrorInfoException {
		try {
			CommentEntity commentEntity = taskMapper.getCommentById(commentId);
			if (commentEntity == null) {
				throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FIND_COMMENT_NULL));
			}
			return commentEntity;
		} catch (Exception e) {
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.INTERNAL_SERVER_ERROR, ErrorCode.FIND_COMMENT_NULL));
		}
		
	}

	@Override
	public int deleteCommentById(Long commentId) throws GlobalErrorInfoException {
		return deleteCommentById(getCommentById(commentId)) ;
	}

	@Override
	public int deleteCommentById(CommentEntity commentEntity) throws GlobalErrorInfoException {
		try {

			int i = taskMapper.deleteCommentById(commentEntity.getCommentId());

			if(i > 0 && commentEntity.getContentType()  == CommentEntity.COMMENT_TYPE_IMG) {
				fileService.deleteFileByUUID(commentEntity.getUuid());
				/*netDiskMapper.removeWithUuid(commentEntity.getUuid());*/

				/**
				 * 删除评论 推送取消
				 * （删除评论不影响网盘文件）
				 */
//				try{
//					HttpServletRequest request = HttpKit.getRequest();
//					Long controlUser = Long.valueOf(request.getAttribute("loginUserId").toString());
//					String userFlag = request.getAttribute("userFlag").toString();
//
//					FileEntity fileEntity = this.fileService.getById(Integer.valueOf(commentEntity.getContent()));
//
//					String uuid = commentEntity.getUuid();
//					Integer circleId = this.taskMapper.getCircleIdByTaskId(Integer.valueOf(commentEntity.getTaskId().toString()));
//
//					NetDisk netDisk = netDiskMapper.getByUUID(uuid);
//
//					//发送socket通知
//					websocketService.sendCircle(controlUser, Long.valueOf(circleId), WebsocketService.CirclePropertise.NET_DISK_FILE_MODIFY, WebsocketService.Control.DELETE, netDisk, userFlag);
//
//				}catch (Exception e){
//					e.printStackTrace();
//					logger.error(e.getMessage());
//				}
			}

			if (i == 0) {
				throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.DELETE_COMMENT_FAIL));
			}
			return i;
		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.INTERNAL_SERVER_ERROR, ErrorCode.DELETE_COMMENT_FAIL));
		}
	}

	@Override
	public boolean userHasTask(Long userId, Long taskId) {
		try {
			return taskMapper.userControlTask(taskId,userId);
		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
			return false;
		}
		
	}

	/**
	 * 获取用户的昵称
	 * @return
	 */
	@Override
	public String getUserNameByTask(Long taskId, Long userId){
		return taskMapper.getUserNameByTask(taskId,userId) ;
	}


	/**
	 * 更新用户查看任务评化的位置
	 * @param taskId
	 * @param userId
	 * @return
	 */
	@Override
	public int updateUserReadLastPosition(Long taskId, Long userId,String userFlag){
		int ret;
		if(taskMapper.existUserReadLastPosition(taskId,userId)) {
			ret = taskMapper.updateUserReadLastPosition(taskId,userId) ;
		}else {
			ret = taskMapper.insertUserReadLastPosition(taskId,userId) ;
		}
		JSONObject json = new JSONObject() ;
		json.put("taskId",taskId) ;
		json.put("parentTaskId",getParentTaskId(taskId)) ;
		websocketService.sendCircle(userId,selectCircleIdByTask(taskId,userId), WebsocketService.CirclePropertise.TASK_USER_READ_POSITION, WebsocketService.Control.MODIFY,json,userFlag);
		return ret ;
	}

	@Override
	public Integer getCircleIdByTaskId(Integer taskId) {
		return this.taskMapper.getCircleIdByTaskId(taskId);
	}

	/**
	 * 更新任务提醒
	 * @param taskRemindEntity
	 * @param controlUser
	 */
	@Override
	public TaskRemindEntity updateTaskRemind(Long taskId,Date planFinishTime, TaskRemindEntity taskRemindEntity, Long controlUser) throws Exception {
		int res ;
		if(taskMapper.existTaskRemind(taskId)) {
			res = taskMapper.updateTaskRemind(taskRemindEntity) ;
		}else {
			res = taskMapper.insertTaskRemind(taskRemindEntity) ;
		}

		if(res != 0) {
			Long runTime = null;
			switch (TaskRemind.getTaskRemind(taskRemindEntity.getRemindMoveUpType())){
				case REMIND_TYPE_DAY:
					runTime = planFinishTime.getTime() - taskRemindEntity.getRemindMoveUp() * DAY ;
					break ;
				case REMIND_TYPE_HOUR:
					runTime =planFinishTime.getTime() - taskRemindEntity.getRemindMoveUp() * HOUR;
					break ;
				case REMIND_TYPE_MINUTE:
					runTime = planFinishTime.getTime() - taskRemindEntity.getRemindMoveUp() * MINUTE;
					break ;
			}
			System.out.println("----------"+new Date(runTime));
			jobAndTrigger.addTaskJob(taskId,runTime);
		}

		return getTaskRemind(taskRemindEntity.getTaskId(),controlUser) ;
	}

	/**
	 * 删除任务提醒
	 * @param controlUser
	 */
	@Override
	public int deleteTaskRemind(Long taskId, Long controlUser) throws Exception {
		int res = 0  ;
		if(taskMapper.existTaskRemind(taskId)) {
			res = taskMapper.deleteTaskRemind(taskId) ;
		}
		jobAndTrigger.deleteTaskJob(taskId);
		return res ;
	}

	/**
	 * 查找任务的提醒
	 * @param taskId
	 * @param controlUser
	 * @return
	 * @throws Exception
	 */
	@Override
	public TaskRemindEntity getTaskRemind(Long taskId, Long controlUser) throws Exception {
		return taskMapper.getTaskRemind(taskId) ;
	}

	/**
	 * 查看任务是否被删除,true为已删除,false为未删除
	 * @param taskId
	 * @return
	 */
	@Override
	public Boolean isdeleted(Long taskId){
		return taskMapper.isdeleted(taskId) ;
	}

	/**
	 * 查看任务是否是子任务,true为子任务,false 不是子任务
	 * @param taskId
	 * @return
	 */
	@Override
	public Boolean isSubTask(Long taskId){
		return taskMapper.isSubTask(taskId) ;
	}

	/**
	 * 查找父任务ID
	 * @param taskId
	 * @return
	 */
	@Override
	public Long getParentTaskId(Long taskId){
		return taskMapper.getParentTaskId(taskId) ;
	}

	/**
	 * 查询圈子用户刚刚创建的任务
	 * @Param circleId
	 * @Param userId
	 * @Param limit条数
	 * @return
	 */
	@Override
	public List<TaskEntity> selectJustCreateTask(Long circleId, Long userId,Long limit){
		return taskMapper.selectJustCreateTask(circleId,userId,limit) ;
	}


	/**
	 * 查询圈子用户刚刚创建的任务的数量
	 * @Param circleId
	 * @Param userId
	 * @return
	 */
	@Override
	public Long selectLookJustCreateTaskCount(Long circleId, Long userId){
		return taskMapper.selectJustCreateTaskCount(circleId,userId) ;
	}

	/**
	 * 更新圈子用户查看刚刚创建的任务的时间
	 * @Param circleId
	 * @Param userId
	 * @return
	 */
	@Override
	public int updateLookJustCreateTaskTime(Long circleId, Long userId,String userFlag){
		websocketService.sendToCircleUserNotifi(userId,userId,circleId,WebsocketService.NotifiPropertise.USER_CIRCLE_JUSTLOOK_TASK_POSITION,null,userFlag);
		return taskMapper.updateJustCreateTaskTime(circleId,userId) ;

	}

}
